package com.mobi.Survey;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.ListView;

import com.appbucks.sdk.AppBucksBanner;
import com.mobi.Survey.controller.DefaultSurveyXmlParser;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.User;
import com.mobi.Survey.model.SurveyTable;
import com.mobi.Survey.uicomponents.SurveyCellButton;
import com.mobi.Survey.utils.Device;
import com.mobi.Survey.utils.Helper;

/**
 * 
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyListScreen.java This class is responsible for displaying survey
 */
public class SurveyListScreen extends AbstractScreen
{
	private AppBucksBanner banner;
	private ListView lvSurveys;
	private View tvNoData;

	private AbstractAdapterSurveyList adapter;
	public static boolean reSynch = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		setTitle(User.getInstance().getLayoutName());

		// if there is no survey in database we will download default surveys
		// from remote server
		if (SurveyPojo.getTotalSurveys(this) == 0)
		{
			new DefaultSurveyDownloadTask().execute();
		} else
		{
			reSynch = true;
		}

		Device.getInstance().init(this);

		if (!Device.isSdPresentForReadWrite()
				&& !Helper.createDirIfNotExists(Helper.APP_FOLDER))
		{
			showAlert(Messages.DIR_CREATE_ERROR);
		}

		// Set Header View background
		showHeaderImage(User.getInstance().getListImage());

		if (User.getInstance().isShowAds()
				&& Helper.isNetworkAvailable(getBaseContext()) && adsEnabled)
		{
			if (banner.getVisibility() == View.GONE)
			{
				banner.setVisibility(View.VISIBLE);
			}
			banner.showAd();
		}

	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo)
	{
		if (v instanceof SurveyCellButton)
		{
			final SurveyCellButton cell = (SurveyCellButton) v;
			if (null != cell.getSurveyForButton().getSubscription()
					&& !cell.getSurveyForButton().getSubscription().isNull())
			{
				final Intent i = new Intent(this, SurveyInformation.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				if (null != cell.getSurveyForButton().getTxtButtonInformation()
						&& cell.getSurveyForButton().getTxtButtonInformation()
								.trim().length() > 0)
				{
					menu.add("Information").setIntent(i);
					// menu.add(
					// cell.getSurveyForButton().getTxtButtonInformation()
					// .trim()).setIntent(i);

				} else
				{
					menu.add("Information").setIntent(i);
				}

			}
			if (cell.getSurveyForButton().isAnswered()
					&& null != cell.getSurveyForButton()
							.getTxtBtnCorrectAnswer()
					&& cell.getSurveyForButton().getTxtBtnCorrectAnswer()
							.length() > 0)
			{
				Intent i = new Intent(this, SurveyAnswersScreen.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				menu.add(cell.getSurveyForButton().getTxtBtnCorrectAnswer())
						.setIntent(i);
			}

			if (null != cell.getSurveyForButton().getTxtBtnSurveyResult()
					&& cell.getSurveyForButton().getTxtBtnSurveyResult()
							.length() > 0)
			{
				Intent i = new Intent(this, AggregateResultScreen.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				menu.add(cell.getSurveyForButton().getTxtBtnSurveyResult())
						.setIntent(i);
			}
			super.onCreateContextMenu(menu, v, menuInfo);
		}

	}

	@Override
	protected void onStart()
	{

		super.onStart();

	}

	@Override
	protected void onResume()
	{

		super.onResume();

		Helper.createDirIfNotExists(Helper.APP_FOLDER);

		if (reSynch)
		{
			new LoadSurveyFromDB().execute();

			reSynch = false;
		}

	}

	private class LoadSurveyFromDB extends AsyncTask<Integer, Integer, Integer>
	{
		ProgressDialog progressDialog = null;

		@Override
		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyListScreen.this, "",
						Messages.FETCHING_SURVEY);
				lvSurveys.setAdapter(null);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}

		@Override
		protected void onPostExecute(Integer result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			if (adapter.getCount() == 0)
			{
				tvNoData.setVisibility(View.VISIBLE);
			} else
			{
				tvNoData.setVisibility(View.GONE);
				lvSurveys.setAdapter(adapter);
			}

			progressDialog.dismiss();

		}

		@Override
		protected Integer doInBackground(Integer... arg0)
		{
			SurveyTable surveyTable = new SurveyTable(SurveyListScreen.this);

			adapter.dispose();

			adapter.setData(surveyTable
					.getSurveysWithSubscriptions(SurveyListScreen.this));

			adapter.notifyDataSetChanged();

			surveyTable.closeDB();
			return null;
		}
	}

	@Override
	protected void onStop()
	{

		super.onStop();

	}

	@Override
	protected void initUiVars()
	{
		lvSurveys = (ListView) findViewById(R.id.lvSurveys);
		tvNoData = findViewById(R.id.tvNoData);
		// Added to support ads banner
		banner = (AppBucksBanner) findViewById(R.id.banner);
		// Image header added now user logins WS will return Banner image and
		// its size
		headerImage = findViewById(R.id.headerImage);
		initializeProperAdapter();

	}

	private void initializeProperAdapter()
	{

		switch (AbstractAdapterSurveyList.getLayoutId())
		{
		case LayoutIds.SURVEY_ROW_SMALL_0:
		case LayoutIds.SURVEY_ROW_MEDIUM_1:
		case LayoutIds.SURVEY_ROW_LARGE_2:
			adapter = new CustomAdapterSurveys(this);
			break;

		case LayoutIds.SURVEY_ROW_SMALL_ICON_3:
		case LayoutIds.SURVEY_ROW_MEDIUM_ICON_4:
		case LayoutIds.SURVEY_ROW_LARGE_ICON_5:
			adapter = new AdapterSurveyListCell(this);
			break;
		default:
			adapter = new AdapterSurveyListCell(this);

		}

	}

	@Override
	protected int getLayoutId()
	{

		return LayoutIds.SURVEY_LIST;
	}

	@Override
	protected void onRelease()
	{
		adapter.dispose();
		adapter = null;

		lvSurveys.setAdapter(null);
		headerImage.setBackgroundDrawable(null);

		User.release();

	}

	public void onClick(final SurveyClick data)
	{
		if (data.getViewId() == R.id.btnSurveyInfo)
		{
			onBtnSurveyInfo(data.getSurvey());

		} else if (data.getViewId() == R.id.btnStartSurvey)
		{
			onBtnSurveyStart(data.getSurvey());

		} else if (data.getViewId() == R.id.btnSurveyResult)
		{
			onBtnSurveyResult(data.getSurvey());

		} else if (data.getViewId() == R.id.btnAnswer)
		{
			onBtnAnswer(data.getSurvey());
		}

	}

	private void onBtnAnswer(final SurveyPojo sp)
	{

		switchScreenTo(SurveyAnswersScreen.class, Long.valueOf(sp.getId()));

	}

	private void onBtnSurveyResult(final SurveyPojo sp)
	{

		switchScreenTo(AggregateResultScreen.class, Long.valueOf(sp.getId()));

	}

	private void onBtnSurveyStart(final SurveyPojo sp)
	{

		if (sp.isShowAllControls()) // Show all controls on single screen
			switchScreenTo(SurveyDetailAllControls.class,
					Long.valueOf(sp.getId()));
		else
		{
			// show one control/screen
			switchScreenTo(SurveyDetailSingleControl.class,
					Long.valueOf(sp.getId()));
		}
	}

	private void onBtnSurveyInfo(final SurveyPojo sp)
	{

		switchScreenTo(SurveyInformation.class, Long.valueOf(sp.getId()));

	}

	/**
	 * Download default surveys from remote location
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	private class DefaultSurveyDownloadTask extends
			AsyncTask<String, Object, Object>
	{
		private ProgressDialog progressDialog = null;
		private boolean gotSurvey = false;
		private String responseMsg = null;
		private List<SurveyPojo> surveys;

		protected Object doInBackground(String... params)
		{

			try
			{
				final DefaultSurveyXmlParser parser = new DefaultSurveyXmlParser();
				parser.parse(getResources().getString(
						R.string.default_survey_url));
				List<SurveyPojo> defSurveys = parser.getDefaultSurveys();
				if (defSurveys != null && defSurveys.size() > 0)
				{
					SurveyPojo.commit(SurveyListScreen.this, defSurveys);
					surveys = defSurveys;
					gotSurvey = true;

					for (final SurveyPojo survey : defSurveys)
					{
						final String surveyIcon = survey.getIconAddress();

						final int hash = Helper.getHashNameFromUrl(surveyIcon);
						String localPath = Helper.getTempFile(hash + "");

						if (Helper.isFileExist(localPath))
						{
							Bitmap b = Helper.decode(localPath, 3);
							survey.setBitmapIcon(b);
						} else
						{
							survey.setBitmapIcon(null);
						}

					}

				}

			} catch (MalformedURLException e)
			{
				responseMsg = Messages.INVALID_URL;

			} catch (IOException e)
			{
				responseMsg = Messages.INVALID_HOST_INTERNET_CONNECTION;
				e.printStackTrace();

			} catch (SAXException e)
			{

				e.printStackTrace();
				responseMsg = Messages.INVALID_SURVEY_XML;
			} catch (RuntimeException e)
			{
				responseMsg = e.getMessage();
			}

			return null;
		}

		protected void onPostExecute(Object result)
		{

			super.onPostExecute(result);
			progressDialog.dismiss();
			progressDialog = null;
			if (gotSurvey)
			{
				tvNoData.setVisibility(View.GONE);
				adapter.setData(surveys);
				lvSurveys.setAdapter(adapter);

			} else
			{
				tvNoData.setVisibility(View.VISIBLE);
			}
			if (responseMsg != null)
			{
				showLongToast(responseMsg);
			}
		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyListScreen.this, "",
						Messages.FETCHING_SURVEY);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

	public void onBackPressed()
	{
		super.onBackPressed();

		finish();

	}

}
